package com.jsy.common.util.bytecode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * jar包搜索内容工具类
 * @Author: jsy
 * @Date: 2021/4/29 23:06
 */
public class JarSearcher {
    public static void main(String[] args) {
//        String jarFilePath = "path/to/your-jar-file.jar";
//        String jarFilePath = "F:\\repository\\org\\jeecgframework\\jimureport\\jimureport-spring-boot-starter\\1.6.4\\jimureport-spring-boot-starter-1.6.4.jar";
        String jarFilePath = "F:\\repository\\org\\jeecgframework\\jimureport\\jimureport-spring-boot-starter\\1.9.0\\jimureport-spring-boot-starter-1.9.0.jar";
//        String jarFilePath = "E:\\汇思工作\\新工作文档\\洛阳光电所\\积木报表\\wethink-jm-report-1.0-SNAPSHOT20250401.jar";
//        String searchString = "vip";
//        String searchString = "view";
//        String searchString = "error.ftl";
        String searchString = "AES";
        System.out.println("===="+searchString);
        boolean found = false;

        int count = 0;
        try (ZipFile zipFile = new ZipFile(jarFilePath)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                count++;
                ZipEntry entry = entries.nextElement();

                if (entry.isDirectory()) {
                    continue; // Skip directories
                }
                String name = entry.getName();
                if (name.contains(searchString)){
                    System.out.println("Found name:"+name);
                }
                try (InputStream is = zipFile.getInputStream(entry);
                     BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.contains(searchString)) {
                            System.out.println("Found in: " + entry.getName());
                            System.out.println("Line: " + line);
                            found = true;
                            break; // Optionally break to stop after first match
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!found) {
            System.out.println("String not found in the jar.");
        }
        System.out.println("Total entries: " + count);
    }
}